﻿#include "CommunicationManager.h"
#include "JsonUtils.h"
#include "QJsonObject"
#include "BaseModbus.h"
#include "ZmqSubscriber.h"
#include "QSerialPortModbus.h"
#include "SerialModbus.h"
#include "WaitUtils.h"

CommunicationManager::CommunicationManager(QObject *parent) : BaseManager(parent)
{
    _factory=new BaseCommunicationFactory();
}

void CommunicationManager::InitConfig()
{
    BaseManager::InitConfig();
    _monitorId=startTimer(10000);
}

CommunicationManager &CommunicationManager::Instance()
{
    static CommunicationManager _instance;
    return _instance;
}

CommunicationManager::~CommunicationManager()
{
}


void CommunicationManager::SetEnableMonitor(bool enableMonitor)
{
    _enableMonitor=enableMonitor;
}

void CommunicationManager::timerEvent(QTimerEvent *)
{
    if(!_enableMonitor)
    {
        return;
    }

    _isMonitoring=true;
    QList<BaseCommunication*> items=BaseManager::GetItems<BaseCommunication>();
    for(BaseCommunication* comm:items)
    {
        if(!comm->IsConnected())
        {
            comm->Connect();
            WaitUtils::WaitMsNoException(1000);
            qDebug()<<comm->Name()<<"重连中..."<<comm->IsConnected();
        }
    }
    _isMonitoring=false;
}

QList<BaseCommunication *> CommunicationManager::GetCommunications(QJsonArray names)
{
    return BaseManager::GetItems<BaseCommunication>(names);
}

void CommunicationManager::WaitForEnd()
{
    killTimer(_monitorId);
    for(auto item:GetNames())
    {
        BaseCommunication* comm=BaseManager::GetItem<BaseCommunication>(item);
        qDebug()<<"dispose "<<comm->Name();
        comm->Dispose();
    }
}
